package com.jy.rhin.infra.service;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: lww
 * @Date: 2022/11/16 14:44
 */

@Service
public class CacheService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Value("${spring.application.name}")
    String appName;

    private static final String KEY_NAME = "now-date-total";

    String keyTemplate = "%s:%s:%s";

    /**
     * 获取当天的消息通知数
     *
     * @param nowDate
     * @return
     */
    public Integer getNowDateTotalCache(String nowDate) {
        String cacheKey = createKey(nowDate);
        Boolean hasKey = stringRedisTemplate.hasKey(cacheKey);
        if (Boolean.FALSE.equals(hasKey)) {
            return null;
        }
        String value = stringRedisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        return Integer.valueOf(value);
    }

    /**
     * 设置当天的消息通知数缓存
     *
     * @param nowDate
     * @param total
     * @return
     */
    public void setNowDateTotalCache(String nowDate, Integer total) {
        String cacheKey = createKey(nowDate);
        Long zeroTimeInterval = getZeroTimeInterval();
        stringRedisTemplate.opsForValue().set(cacheKey, total.toString(), zeroTimeInterval, TimeUnit.SECONDS);
    }

    /**
     * 当天的消息通知数缓存+1
     *
     * @param nowDate
     */
    public void addNowDateTotalCache(String nowDate) {
        String cacheKey = createKey(nowDate);
        stringRedisTemplate.opsForValue().increment(cacheKey, 1);
    }

    /**
     * 判断缓存是否存在
     * @param nowDate
     * @return
     */
    public Boolean hasKey(String nowDate) {
        String cacheKey = createKey(nowDate);
        return stringRedisTemplate.hasKey(cacheKey);
    }

    /**
     * 删除当天的设置缓存
     *
     * @param nowDate
     */
    public void removeNowDateTotalCache(String nowDate) {
        String cacheKey = createKey(nowDate);
        stringRedisTemplate.delete(cacheKey);
    }

    /**
     * 获取当前时间与晚上十二点的秒差
     *
     * @return
     */
    private Long getZeroTimeInterval() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        //当前时间与晚上十二点的秒差
        return (calendar.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }

    /**
     * 创建缓存key
     *
     * @param nowDate
     * @return
     */
    private String createKey(String nowDate) {
        return String.format(keyTemplate, appName, KEY_NAME, nowDate);
    }

}
